exports.MainView = function() {
	var instance = Ti.UI.createView({
		backgroundColor:'#000'
	});
	
	//Get data for tableview
	var categories = [];
	var rows = Util.localDb.execute('SELECT * FROM test_category');
	while (rows.isValidRow()) {
	  	categories.push({
	    	title: rows.fieldByName('name'),
	    	id: rows.fieldByName('id'),
	    	className: 'top',
	    	hasChild: true
	  	});
		rows.next();
	}
	rows.close();
	
	var categoryTableView = Ti.UI.createTableView({data: categories});
	var state = {expandedRow: -1,
				childRows: 0,
				highlight: -1,
				urls: Util.urls() };
	categoryTableView.addEventListener('click', function(e) {
		Ti.API.debug('Row clicked: ' + e.index + ' Id: ' + e.rowData.id + ' Children: ' + state.childRows + ' Last selected: ' + state.expandedRow);
		if (e.rowData.hasDetail == true) {	
			// Show the test
			Ti.API.debug("Show test for: " + e.rowData.id);
			state.highlight = -1;
		}
		else {
			state.highlight = e.index - state.childRows;
			// Acccordian toggle List all tests in the category
			if (state.expandedRow > -1) {
				removeRows(categoryTableView, state.expandedRow, state.childRows);
				state.childRows = 0;				
			}

			if (state.expandedRow != e.index) {
				var loc = state.highlight; 
				state.expandedRow = state.highlight;
				var rows = Util.localDb.execute('SELECT * FROM tests WHERE category = ?', [e.rowData.id]);
				var i = 0;
				while (rows.isValidRow()) {
					// TODO: Compute URL from Data
					i++;
					var icon = i % 5 == 0 ? state.urls['stop'] : (i % 5 == 1 ? state.urls['none']: (i % 5 == 2 ? state.urls['go']: (state.urls['yield'])));
					Ti.API.debug('Image is ' + icon);
					state.childRows++;
					var row = Ti.UI.createTableViewRow({
	    				className: 'test',
						hasDetail:true,
						indentationLevel:2,
						leftImage: icon,
	    				id: rows.fieldByName('id'),
						title: rows.fieldByName('name')
					});
	//				row.add(testList);
					categoryTableView.insertRowAfter(loc++ ,row,{});
					rows.next();
				}
				rows.close();				
			}
			else {
				state.expandedRow = -1;
			}
	
		}
		
		// Show highlighting for the row that was clicked
		if (Titanium.Platform.name != 'android') {
			categoryTableView.selectRow(state.highlight);
		}		
	});


	instance.add(categoryTableView);
	
	return instance;
};

function createRow(name, selected) {
	
	var test = new TestView.TestView({
		title: name,
		selected: selected 
	});
	var testRow = Ti.UI.createTableViewRow({
		className: 'top'
	});
	testRow.add(test);
	
	return testRow;
}

function removeRows(tv, start, count) {
	var i = start + count;
	while (i > start) {
		Ti.API.debug("Removing row at: " + i);
		tv.deleteRow(i--,{});
	}
}
